package com.aaronprj.school.mbooks.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.aaronprj.common.entities.SgmenuEntityManager;
import com.aaronprj.common.entities.mbooks.BookItem;
import com.aaronprj.common.entities.mbooks.Comment;
import com.aaronprj.common.enums.mbooks.Course;
import com.aaronprj.common.enums.mbooks.ItemCategory;
import com.aaronprj.common.utils.EnumHelper;
import com.aaronprj.common.utils.mbooks.SystemInitialHelper;
import com.aaronprj.common.web.resource.ResourceServices;
import com.aaronprj.common.web.uivo.BaseEntity;
import com.aaronprj.school.mbooks.uivo.UIBookItem;
import com.aaronprj.school.mbooks.uivo.UIBookMenu;
import com.aaronprj.school.mbooks.uivo.UIComment;

@Path("/item")
public class ItemResource extends ResourceServices{

    @POST
	@Produces(MediaType.APPLICATION_JSON)
	public String updateItem(
			 @QueryParam("id") int id, 
			 @QueryParam("name") String name, 
			 @QueryParam("discription") String discription,
			 @QueryParam("courseId") int courseId, 
			 @QueryParam("author") String author,
			 @QueryParam("isdn") String isdn, 
			 @QueryParam("publisher") String publisher, 
			 @QueryParam("price") double price, 
			 @QueryParam("stock") int stock, 
			 @QueryParam("imgpath") String imgpath){

		BaseEntity entity = generateResult(BaseEntity.class, true, "", "");
		try {
			Course course = EnumHelper.getEnumValue(Course.class, courseId);
			
			BookItem item;
			if(id == 0){
				item = new BookItem();
			}else{
				item = (BookItem)SgmenuEntityManager.findItem(BookItem.class, id);
			}
			
			item.setName(name);
			item.setDiscription(discription);
			item.setCategory(course.getCategory());
			item.setCourse(course);
			item.setAuthor(author);
			item.setIsdn(isdn);
			item.setPublisher(publisher);
			item.setPrice(price);
			item.setStock(stock);
			
			item.setImgpath("pix/"+imgpath.substring(imgpath.lastIndexOf("/") + 1));
			

			SgmenuEntityManager.saveItem(item, id == 0);
		} catch (Exception e) {
			entity.setSuccess(false);
			e.printStackTrace();
		}
		return writeValueAsString(entity);
	}
	
	@Path("/delete/{id}")
    @POST
	@Produces(MediaType.APPLICATION_JSON)
	public String deleteItem(@PathParam("id") int itemid){
		
		SgmenuEntityManager.deleteItem(BookItem.class, itemid);
		BaseEntity entity = generateResult(BaseEntity.class, true, "Delete item successfull", "");
		return writeValueAsString(entity);
	}
	
	@Path("/hits/{id}/{hits}")
    @POST
	@Produces(MediaType.APPLICATION_JSON)
	public String updateItemHits(@PathParam("id") int itemid, @PathParam("hits") int hits){
		
		BookItem item = (BookItem)SgmenuEntityManager.findItem(BookItem.class, itemid);
		
		item.setHits(hits);

		SgmenuEntityManager.saveItem(item, false);
		BaseEntity entity = generateResult(BaseEntity.class, true, "", "");
		return writeValueAsString(entity);
	}
	
	@Path("/comment")
    @POST
	@Produces(MediaType.APPLICATION_JSON)
	public String addItemComment(@QueryParam("itemId") int itemId, 
			 @QueryParam("customerId") int customerId,
			 @QueryParam("customerName") String customerName, 
			 @QueryParam("content") String content){

		BaseEntity entity = generateResult(BaseEntity.class, true, "", "");
		try {
			Comment cmt = new Comment();
			cmt.setItemId(itemId);
			cmt.setCustomerId(customerId);
			cmt.setCustomerName(customerName);
			cmt.setContent(content);
			cmt.setCreateDate(new Date());
			
			SgmenuEntityManager.saveItem(cmt, false);
		} catch (Exception e) {
			entity.setSuccess(false);
			e.printStackTrace();
		}
		return writeValueAsString(entity);
	}
	
	@SuppressWarnings("unchecked")
	@Path("/comments/{id}")
    @GET
	@Produces(MediaType.APPLICATION_JSON)
	public String getItemComments(@PathParam("id") int id){
		List<Comment> comments = (List<Comment>) SgmenuEntityManager.getItems("Comment.findByItem","itemId",id);

		if(null == comments || comments.isEmpty()){
			return this.writeValueAsString(generateResult(UIBookMenu.class, true, "No record found", ""));
		}else{
			List<UIComment> uics = new ArrayList<UIComment>();
			for(Comment c:comments){
				uics.add(new UIComment(c.getId(),c.getCustomerName(),c.getContent(),c.getCreateDate()));
			}
			
	    	return writeValueAsString(uics);
		}

	}

	@SuppressWarnings("unchecked")
	@Path("/items")
    @GET 
	@Produces(MediaType.APPLICATION_JSON)
    public String getItems() {
		List<BookItem> fis = (List<BookItem>) SgmenuEntityManager.getAllEntities("BookItem");
		if(null == fis || fis.isEmpty()){

			//if first time login,,have to initial the food item data
			SystemInitialHelper.createBookItems();
			
			fis = (List<BookItem>) SgmenuEntityManager.getAllEntities("BookItem");
		}

		if(null == fis || fis.isEmpty()){
			return this.writeValueAsString(generateResult(UIBookMenu.class, true, "No record found", ""));
		}

    	return writeValueAsString(buildUIBookMenu(fis));
	}
	
	@SuppressWarnings("unchecked")
	@Path("/items/category/{category}")
    @GET 
	@Produces(MediaType.APPLICATION_JSON)
    public String getItemsByCategory(@PathParam("category") int category) {
		
		ItemCategory categoryobj = EnumHelper.getEnumValue(ItemCategory.class, category);
		
		List<BookItem> fis = (List<BookItem>) SgmenuEntityManager.getItems("BookItem.findByCategory", "category", categoryobj);
		if(null == fis || fis.isEmpty()){


			fis = (List<BookItem>) SgmenuEntityManager.getAllEntities("BookItem");
			//if first time login,,have to initial the food item data
			if(null == fis || fis.isEmpty()){
				SystemInitialHelper.createBookItems();
				fis = (List<BookItem>) SgmenuEntityManager.getItems("BookItem.findByCategory", "category", categoryobj);
			}else{
				fis = null;
			}
		}
		
		if(null == fis || fis.isEmpty()){
			return this.writeValueAsString(generateResult(UIBookMenu.class, true, "No record found", ""));
		}

    	return this.writeValueAsString(buildUIBookMenu(fis));
	}
	
	@SuppressWarnings("unchecked")
	@Path("/items/course/{course}")
    @GET 
	@Produces(MediaType.APPLICATION_JSON)
    public String getItemsByCategoryAndCourse(@PathParam("course") int course) {
		
		Course courseobj = EnumHelper.getEnumValue(Course.class, course);

		List<BookItem> fis = (List<BookItem>) SgmenuEntityManager.getItems("BookItem.findByCourse", "course", courseobj);
		if(null == fis || fis.isEmpty()){
			fis = (List<BookItem>) SgmenuEntityManager.getAllEntities("BookItem");
			//if first time login,,have to initial the food item data
			if(null == fis || fis.isEmpty()){
				SystemInitialHelper.createBookItems();
				fis = (List<BookItem>) SgmenuEntityManager.getItems("BookItem.findByCourse", "course", courseobj);
			}else{
				fis = null;
			}
		}
		
		if(null == fis || fis.isEmpty()){
			return this.writeValueAsString(generateResult(UIBookMenu.class, true, "No record found", ""));
		}

    	return this.writeValueAsString(buildUIBookMenu(fis));
	}
	
	
	@SuppressWarnings("unchecked")
	@Path("/items/fulltext/{keyword}")
    @GET 
	@Produces(MediaType.APPLICATION_JSON)
    public String getItemsByKeyWords(@PathParam("keyword") String keyword, @QueryParam("course") String courses,@QueryParam("author") String author) {
		
		List<BookItem> fis = SgmenuEntityManager.getItemsFullText(keyword);
		if(null == fis || fis.isEmpty()){
			fis = (List<BookItem>) SgmenuEntityManager.getAllEntities("BookItem");
			//if first time login,,have to initial the food item data
			if(null == fis || fis.isEmpty()){
				SystemInitialHelper.createBookItems();
				fis = SgmenuEntityManager.getItemsFullText(keyword);
			}else{
				fis = null;
			}
		}

		if(null == fis || fis.isEmpty()){
			return this.writeValueAsString(generateResult(UIBookMenu.class, true, "No record found", ""));
		}

    	return this.writeValueAsString(buildUIBookMenu(fis, courses, author));
	}
	

	private UIBookMenu buildUIBookMenu(List<BookItem> fis){
		return buildUIBookMenu(fis, "", "");
	}
	private UIBookMenu buildUIBookMenu(List<BookItem> fis, String courses, String author){
		boolean filterCourse = null != courses && !"".equals(courses);
		boolean filterAuthor = null != author && !"".equals(author);
		
		
		UIBookMenu ufm = generateResult(UIBookMenu.class, true, "", "");
		for(BookItem fi:fis){
			if(filterCourse){
				if(courses.indexOf(fi.getCourse().getDisplayName()) == -1 && fi.getCourse().getDisplayName().indexOf(courses) == -1){
					continue;
				}
			}
			if(filterAuthor){
				if(author.indexOf(fi.getAuthor()) == -1 && fi.getAuthor().indexOf(author) == -1){
					continue;
				}
			}
			
			UIBookItem item = new UIBookItem();
			item.setId(fi.getId());
			item.setAuthor(fi.getAuthor());
			item.setDiscription(fi.getDiscription());
			item.setImgpath(fi.getImgpath());
			item.setIsdn(fi.getIsdn());
			item.setPublisher(fi.getPublisher());
			item.setName(fi.getName());
			item.setPrice(fi.getPrice());
			item.setCourseId(fi.getCourse().getValue());
			item.setStock(fi.getStock());
			item.setActualPrice(fi.getPrice()*0.85);
			
			ufm.addUIItem(fi.getCategory(), item);
		}
		return ufm;
		
	}
	
	
}
